package com.jsyxdl.k3cloud.listener;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONObject;
import com.hustcad.plm.pdm.baseline.module.dto.TyplmBaseLineMemberObjParam;
import com.hustcad.plm.pdm.baseline.module.vo.TyplmBaseLineObjectVO;
import com.hustcad.plm.pdm.baseline.service.TyplmBaseLineMemberService;
import com.hustcad.plm.pdm.common.model.dto.tableview.TableViewConditionDTO;
import com.hustcad.plm.pdm.common.model.vo.tableview.CompareRowTableViewVO;
import com.hustcad.plm.pdm.common.service.tableview.TyplmAdvanceTableViewService;
import com.hustcad.plm.pdm.ec.module.dto.ECObjData;
import com.hustcad.plm.pdm.flowbusiness.model.entity.FlowChgFormView;
import com.hustcad.plm.pdm.flowbusiness.model.entity.FlowObject;
import com.hustcad.plm.pdm.partbom.dto.ChildPartsFiltersDTO;
import com.hustcad.plm.pdm.partbom.dto.CompareReportDTO;
import com.hustcad.plm.pdm.partbom.dto.CompartReportPartDTO;
import com.hustcad.plm.pdm.partbom.dto.PartBomTree;
import com.hustcad.plm.pdm.partbom.dto.QuerySubstituteLinkDTO;
import com.hustcad.plm.pdm.partbom.service.TyplmPartBomService;
import com.hustcad.plm.pdm.partbom.service.TyplmPartCompareService;
import com.hustcad.plm.pdm.partbom.service.partalternate.TyplmPdmPartAlternateService;
import com.hustcad.plm.pdm.partbom.service.partalternate.TyplmPdmPartSubstituteService;
import com.hustcad.plm.pdm.partbom.vo.*;
//import com.jsyxdl.k3cloud.excel.ProductionChangeOrderUtils;
import com.jsyxdl.k3cloud.listener.handling.*;
import com.jsyxdl.k3cloud.service.ErpWorkedTaskService;
import com.jsyxdl.k3cloud.utils.PlmPartOptionUtils;
import com.jsyxdl.service.ErpPartAlternativeService;
import com.ty.basic.entity.IdentifierEntity;
import com.ty.basic.entity.org.UserDO;
import com.ty.basic.session.TyAccountContext;
import org.apache.commons.lang3.ObjectUtils;

import java.math.BigInteger;
import java.util.*;

/**
 * 变更流程物料清单处理
 */
public class WorkFlowObjectPackageRoutine {

    /**
     * 发布流程监听分流处理
     *
     * @param code
     * @param k3cloud
     * @param flowObject
     * @param userDO   //流程发起人用户对象
     * @return
     * @throws Exception
     */
    public JSONObject erpTaskWorkderRoutine(String code, String k3cloud, String check, FlowObject flowObject,UserDO userDO ) throws Exception {
        K3CloudHttpService k3CloudHttpService = SpringUtil.getBean(K3CloudHttpService.class);
        boolean tdwl = false;
        if ("替代方案物料".equals(k3cloud)) {
            k3cloud = "BOM保存";
            tdwl = true;
        }
        Map<String, Object> executionType = k3CloudHttpService.getExecutionType(code, k3cloud);
        executionType.put("code", code);
        executionType.put("k3cloud", k3cloud);

        String formid = (String) executionType.get("formid");
        String uri = (String) executionType.get("uri");

        if ("BD_MATERIAL".equals(formid)) {
            if ("/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Save.common.kdsvc".equals(uri)) {
                //处理物料全部业务
                MaterialsHandling materialsHandling = new MaterialsHandling();
                return materialsHandling.productionCall(check,executionType, flowObject);
            } else if ("/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.BatchSave.common.kdsvc".equals(
                    uri)) {
                if (tdwl == true) {
                    //替代方案批量处理物料全部业务
                    AlternativeMaterialsHandling alternativeMaterialsHandling = new AlternativeMaterialsHandling();
                    return alternativeMaterialsHandling.productionCall(check,executionType, flowObject);
                } else {
                    //批量处理物料全部业务
                    MaterialsBatchHandling materialsBatchHandling = new MaterialsBatchHandling();
                    return materialsBatchHandling.productionCall(check,executionType, flowObject);
                }

            }

        } else if ("ENG_Substitution".equals(formid)) {
            //处理替代全部业务
            AlternativeSolutionHandling alternativeSolutionHandling = new AlternativeSolutionHandling();
            return alternativeSolutionHandling.productionCall(check,executionType, flowObject);
        } else if ("ENG_BOM".equals(formid)) {
            //处理物料清单全部业务
            BuildBomHandling buildBomHandling = new BuildBomHandling();
            return buildBomHandling.productionCall(executionType, flowObject);
        } else if ("PUR_Requisition".equals(formid)) {
            //处理采购清单全部业务
            ProcurementHandling procurementHandling = new ProcurementHandling();
            return procurementHandling.productionCall(executionType, flowObject,userDO);
        } else if ("STK_OutStockApply".equals(formid)) {
            //处理出库申请单全部业务
            OutboundApplicationHandling outboundApplicationHandling = new OutboundApplicationHandling();
            return outboundApplicationHandling.productionCall(executionType, flowObject,userDO);
        }
        return null;
    }

    /**
     * 变更流程监听分流处理
     *
     * @param code
     * @param k3cloud
     * @param flowChgFormView
     * @return
     * @throws Exception
     */

    public JSONObject erpChangeTaskWorkderRoutine(String check,String code, String k3cloud, String materialsCode,
                                                  String materialsObject,
                                                  String alternativeCode,
                                                  String globalObject,
                                                  String localityObject,
                                                  String reverseReviewCode,
                                                  String reverseReviewObject,
                                                  FlowChgFormView flowChgFormView) throws Exception {


        K3CloudHttpService k3CloudHttpService = SpringUtil.getBean(K3CloudHttpService.class);
        Map<String, Object> resultMap = changeTaskWorkder(flowChgFormView);

        JSONObject resultJson = null;
        if (resultMap != null) {
            if(resultMap.containsKey("jyList")){
                Map<String, Object> executionType = k3CloudHttpService.getExecutionType(code, k3cloud);
                executionType.put("code", code);
                executionType.put("k3cloud", k3cloud);
                List<PartDetailsVO> jyList= (List<PartDetailsVO>) resultMap.get("jyList");
                List<String> disList=new ArrayList<>();
                for(int i=0;i<jyList.size();i++){
                    disList.add(jyList.get(i).getObjectNumber());
                }
                if(disList.size()>0){
                    SubmissionAndReviewHanding.Disabled(executionType,disList);
                }
            }
            //批量处理物料全部业务
            if (resultMap.containsKey("add")) {
                Map<String, Object> materialsBatchType = k3CloudHttpService.getExecutionType(materialsCode,
                                                                                             materialsObject);
                materialsBatchType.put("code", materialsCode);
                materialsBatchType.put("k3cloud", materialsObject);
                List<PartDetailsVO> partDetailsVOList = (List<PartDetailsVO>) resultMap.get("add");
                MaterialsBatchHandling materialsBatchHandling = new MaterialsBatchHandling();
                resultJson = materialsBatchHandling.productionCall(check,materialsBatchType, partDetailsVOList);
                JSONObject Result = resultJson.getJSONObject("Result");
                if (Result != null) {
                    JSONObject ResponseStatus = Result.getJSONObject("ResponseStatus");

                    if (ResponseStatus.getBooleanValue("IsSuccess") == false) {
                        return resultJson;
                    }
                }
            }
            //反审核替代方案
            if (resultMap.containsKey("deleteAlternativeMap")) {
                Map<String, Object> deleteType = k3CloudHttpService.getExecutionType(reverseReviewCode,
                                                                                     reverseReviewObject);
                deleteType.put("code", reverseReviewCode);
                deleteType.put("k3cloud", reverseReviewObject);
                Map<String, List<PartSubstituteVO>> deleeUnAuditMap = (Map<String, List<PartSubstituteVO>>) resultMap.get(
                        "deleteAlternativeMap");
                List<String> numbers = new ArrayList<>();
                if (deleeUnAuditMap != null) {
                    for (Map.Entry<String, List<PartSubstituteVO>> entity : deleeUnAuditMap.entrySet()) {
                        numbers.add(entity.getKey());
                    }
                }

                resultJson = SubmissionAndReviewHanding.unSubmittReview(deleteType, numbers);
                JSONObject Result = resultJson.getJSONObject("Result");
                if (Result != null) {
                    JSONObject ResponseStatus = Result.getJSONObject("ResponseStatus");
                    if (ResponseStatus.getBooleanValue("IsSuccess") == false) {
                        return resultJson;
                    }
                }
            }
            //添加替代方案
            if (resultMap.containsKey("addAlternativeList")) {
                Map<String, Object> globalAlternativeType = k3CloudHttpService.getExecutionType(alternativeCode,
                                                                                                globalObject);
                globalAlternativeType.put("code", alternativeCode);
                globalAlternativeType.put("k3cloud", globalObject);
                List<Map<String, Object>> alternativeList = (List<Map<String, Object>>) resultMap.get(
                        "addAlternativeList");
                AlternativeSolutionHandling alternativeSolutionHandling = new AlternativeSolutionHandling();
                resultJson = alternativeSolutionHandling.productionCall(globalAlternativeType, alternativeList);
                JSONObject Result = resultJson.getJSONObject("Result");
                if (Result != null) {
                    JSONObject ResponseStatus = Result.getJSONObject("ResponseStatus");

                    if (ResponseStatus.getBooleanValue("IsSuccess") == false) {
                        return resultJson;
                    }
                }
                Map<String, Object> localityAlternativeType = k3CloudHttpService.getExecutionType(alternativeCode,
                                                                                                  localityObject);
                localityAlternativeType.put("code", alternativeCode);
                localityAlternativeType.put("k3cloud", localityObject);
                List<Map<String, Object>> localityAlternativeList = (List<Map<String, Object>>) resultMap.get(
                        "addAlternativeList");
                resultJson = alternativeSolutionHandling.productionCall(localityAlternativeType,
                                                                        localityAlternativeList);
                Result = resultJson.getJSONObject("Result");
                if (Result != null) {
                    JSONObject ResponseStatus = Result.getJSONObject("ResponseStatus");

                    if (ResponseStatus.getBooleanValue("IsSuccess") == false) {
                        return resultJson;
                    }
                }
            }
            //更新BOM
            if (resultMap.containsKey("updateBom")) {
                //修改BOM
                Map<String, Object> executionType = k3CloudHttpService.getExecutionType(code, k3cloud);
                executionType.put("code", code);
                executionType.put("k3cloud", k3cloud);

                List<PartBomTree> bomTreeList = (List<PartBomTree>) resultMap.get("updateBom");
                Map<String, String> baseLineMap = (Map<String, String>) resultMap.get("baseLine");

                BuildBomHandling buildBomHandling = new BuildBomHandling();
                resultJson = buildBomHandling.productionCall(executionType, bomTreeList,baseLineMap);
            }
        }

        return resultJson;
    }

    /**
     * 变更流程中获取变更的对象
     *
     * @param flowChgFormView
     * @return
     * @throws Exception
     */
    public Map<String, Object> changeTaskWorkder(FlowChgFormView flowChgFormView) throws Exception {
        PlmPartOptionUtils plmPartOptionUtils = SpringUtil.getBean(PlmPartOptionUtils.class);
        TyplmPartBomService typlmPartBomService = SpringUtil.getBean(TyplmPartBomService.class);
        TyplmPartCompareService typlmPartCompareService = SpringUtil.getBean(TyplmPartCompareService.class);
        TyplmAdvanceTableViewService typlmAdvanceTableViewService = SpringUtil.getBean(
                TyplmAdvanceTableViewService.class);
        TyplmBaseLineMemberService typlmBaseLineMemberService = SpringUtil.getBean(
                TyplmBaseLineMemberService.class);

        if (flowChgFormView.getChgFormVO() != null && flowChgFormView.getChgFormVO().getEcAffectVOS() != null) {


            Map<String, Object> resultMap = new HashMap<>();
            Map<String, ECObjData> newMap = new HashMap<>();
            Map<String, ECObjData> oldMap = new HashMap<>();
            List<PartBomTree> AllBomTreeList = new LinkedList<>();
            Map<String, String> baseLineMap = new HashMap<>();

            List<PartDetailsVO> jyList=new ArrayList<>();


            for (int i = 0; i < flowChgFormView.getChgFormVO().getEcAffectVOS().size(); i++) {
                ECObjData ecObjData = flowChgFormView.getChgFormVO().getEcAffectVOS().get(i);
                if ("ty.inteplm.part.CTyPart".equals(ecObjData.getOtype())) {
                    String baseLineDescription=null;

                    TyplmBaseLineMemberObjParam param=new TyplmBaseLineMemberObjParam();
                    IdentifierEntity objInfo=new IdentifierEntity();
                    objInfo.setOid(ecObjData.getRefObjectOid());
                    objInfo.setOtype(ecObjData.getRefObjectOtype());
                    param.setObjInfo(objInfo);
                    List<TyplmBaseLineObjectVO> baseList=typlmBaseLineMemberService.queryObjMemberInfo(param);
                    if(baseList.size()>0){
                        long baseVal=0;
                        for(int z=0;z<baseList.size();z++){
                            String number=baseList.get(z).getBaseLineInfo().getNumber();
                            number=number.substring(2);
                            long cmdVal=Long.parseLong(number);
                            if(cmdVal>baseVal){
                                baseVal=cmdVal;
                                baseLineDescription=baseList.get(z).getBaseLineInfo().getDisplayname();
                            }
                        }
                    }

                    //获取变更后对象涉及的BOM
                    com.hustcad.plm.pdm.partbom.dto.ExpandBomTreeByFilterDTO expandBomTreeByFilterDTO = new com.hustcad.plm.pdm.partbom.dto.ExpandBomTreeByFilterDTO();
                    expandBomTreeByFilterDTO.setAttrFilterCondition(new ArrayList<>());

                    ChildPartsFiltersDTO childPartsFiltersDTO = new ChildPartsFiltersDTO();
                    childPartsFiltersDTO.setBaseLineOid("");
                    childPartsFiltersDTO.setDate("");
                    childPartsFiltersDTO.setExpandCondition("latest");
                    childPartsFiltersDTO.setLifecycleStateKey("");
                    childPartsFiltersDTO.setPurposeOfBom("");
                    childPartsFiltersDTO.setSpareBom("");
                    childPartsFiltersDTO.setView(ecObjData.getView());
                    List<ChildPartsFiltersDTO> list = new ArrayList<>();
                    list.add(childPartsFiltersDTO);
                    expandBomTreeByFilterDTO.setConditions(list);

                    expandBomTreeByFilterDTO.setExpandLevel("1");
                    expandBomTreeByFilterDTO.setFatherNumber(ecObjData.getObjectNumber());
                    expandBomTreeByFilterDTO.setFatherOid(String.valueOf(ecObjData.getOid()));
                    expandBomTreeByFilterDTO.setFatherOtype(ecObjData.getOtype());
                    expandBomTreeByFilterDTO.setFilterMode("0");
                    expandBomTreeByFilterDTO.setGiveUsesOccurrence("N");
                    expandBomTreeByFilterDTO.setIbaColumns(new ArrayList<>());
                    expandBomTreeByFilterDTO.setIsApplyRoot(false);
                    expandBomTreeByFilterDTO.setIsFilterAttr(false);
                    expandBomTreeByFilterDTO.setIsNeedTranEnum(true);
                    expandBomTreeByFilterDTO.setIsNestedTree(true);
                    expandBomTreeByFilterDTO.setIsQueryIBA(true);

                    PartBomTreeByFilterVO result = typlmPartBomService.expandBomTreeByFilterNew(
                            expandBomTreeByFilterDTO, Boolean.TRUE);
                    PartBomTree partBomTree = result.getPartBomTreeList().get(0);
                    baseLineMap.put(partBomTree.getObjectNumber(),baseLineDescription);

                    if (partBomTree.getChildren().size() == 0) {
                        //不是BOM，取其父级
                        List<BigInteger> partList = new ArrayList<>();
                        partList.add(ecObjData.getRefObjectOid());
                        List<ParentPartDetailVO> plist = typlmPartBomService.queryParentPartByFilter(partList);
                        if (plist.size() > 0) {
                            ParentPartDetailVO parentPartDetailVO = plist.get(0);
                            expandBomTreeByFilterDTO = new com.hustcad.plm.pdm.partbom.dto.ExpandBomTreeByFilterDTO();
                            expandBomTreeByFilterDTO.setAttrFilterCondition(new ArrayList<>());

                            childPartsFiltersDTO = new ChildPartsFiltersDTO();
                            childPartsFiltersDTO.setBaseLineOid("");
                            childPartsFiltersDTO.setDate("");
                            childPartsFiltersDTO.setExpandCondition("latest");
                            childPartsFiltersDTO.setLifecycleStateKey("");
                            childPartsFiltersDTO.setPurposeOfBom("");
                            childPartsFiltersDTO.setSpareBom("");
                            childPartsFiltersDTO.setView(parentPartDetailVO.getView());
                            list = new ArrayList<>();
                            list.add(childPartsFiltersDTO);
                            expandBomTreeByFilterDTO.setConditions(list);

                            expandBomTreeByFilterDTO.setExpandLevel("1");
                            expandBomTreeByFilterDTO.setFatherNumber(parentPartDetailVO.getObjectNumber());
                            expandBomTreeByFilterDTO.setFatherOid(String.valueOf(parentPartDetailVO.getOid()));
                            expandBomTreeByFilterDTO.setFatherOtype(parentPartDetailVO.getOtype());
                            expandBomTreeByFilterDTO.setFilterMode("0");
                            expandBomTreeByFilterDTO.setGiveUsesOccurrence("N");
                            expandBomTreeByFilterDTO.setIbaColumns(new ArrayList<>());
                            expandBomTreeByFilterDTO.setIsApplyRoot(false);
                            expandBomTreeByFilterDTO.setIsFilterAttr(false);
                            expandBomTreeByFilterDTO.setIsNeedTranEnum(true);
                            expandBomTreeByFilterDTO.setIsNestedTree(true);
                            expandBomTreeByFilterDTO.setIsQueryIBA(true);

                            result = typlmPartBomService.expandBomTreeByFilterNew(
                                    expandBomTreeByFilterDTO, Boolean.TRUE);
                            partBomTree = result.getPartBomTreeList().get(0);
                            if (partBomTree.getChildren().size() > 0) {
                                AllBomTreeList.add(partBomTree);

                            }

                        }
                    } else {
                        AllBomTreeList.add(partBomTree);
                    }

                }
            }

            for (int i = 0; i < flowChgFormView.getChgFormVO().getEcAffectVOS().size(); i++) {
                ECObjData ecObjData = flowChgFormView.getChgFormVO().getEcAffectVOS().get(i);
                if ("ty.inteplm.part.CTyPart".equals(ecObjData.getOtype())) {
                    //变更后对象
                    newMap.put(ecObjData.getNumber(), ecObjData);
                }
            }

            for (int i = 0; i < flowChgFormView.getChgFormVO().getEcObjDataVOS().size(); i++) {
                ECObjData ecObjData = flowChgFormView.getChgFormVO().getEcObjDataVOS().get(i);
                if ("ty.inteplm.part.CTyPart".equals(ecObjData.getOtype())) {
                    //变更前对象
                    oldMap.put(ecObjData.getNumber(), ecObjData);
                }
            }

            TableViewConditionDTO conditionDTO = new TableViewConditionDTO();
            conditionDTO.setTableid("partCompareAttributes");
            conditionDTO.setViewgroup("Object_Compare");
            Map<String, CompareRowTableViewVO> conditionMap = typlmAdvanceTableViewService.getUserDefaultComparisonTableView(
                    conditionDTO);
            CompareReportDTO compareReportDTO = new CompareReportDTO();
            Set<Map.Entry<String, CompareRowTableViewVO>> set = conditionMap.entrySet();
            List<String> needCompareAttrList = new ArrayList<>();
            Map<BigInteger, List<String>> needCompareAttrMap = new HashMap<>();
            for (Map.Entry<String, CompareRowTableViewVO> entity : set) {
                CompareRowTableViewVO compareRowTableViewVO = entity.getValue();
                List<JSONObject> jsonObjectList = compareRowTableViewVO.getCompareAttr();
                for (int a = 0; a < jsonObjectList.size(); a++) {
                    needCompareAttrList.add(jsonObjectList.get(a).getString("propertyName"));
                }
                needCompareAttrList.add("oid");
                needCompareAttrMap.put(new BigInteger(entity.getKey()), needCompareAttrList);
            }
            compareReportDTO.setNeedCompareAttr(needCompareAttrMap);
            compareReportDTO.setCompareBomAttrs(true);
            compareReportDTO.setCompareCadRef(true);
            compareReportDTO.setCompareDocRef(true);
            compareReportDTO.setComparePartAttrs(true);
            compareReportDTO.setCompareDescribeDocRef(true);
            List<CompartReportPartDTO> comparePartList = new ArrayList<>();
            Set<Map.Entry<String, ECObjData>> newSet = newMap.entrySet();
            for (Map.Entry<String, ECObjData> entity : newSet) {
                CompartReportPartDTO compartReportPartDTO = new CompartReportPartDTO();
                ECObjData ecObjData = entity.getValue();
                compartReportPartDTO.setRightPartOid(ecObjData.getOid());
                if (oldMap.containsKey(entity.getKey())) {
                    ECObjData ecObjDataOld = oldMap.get(entity.getKey());
                    compartReportPartDTO.setLeftPartOid(ecObjDataOld.getOid());
                }
                comparePartList.add(compartReportPartDTO);
            }

            compareReportDTO.setComparePartList(comparePartList);
            List<CompareReportVO> diff = typlmPartCompareService.compareReport(compareReportDTO);


            List<PartDetailsVO> partDetailsVOList = new ArrayList<>();
            List<PartBomTree> bomTreeList = new LinkedList<>();

            //首先批量创建物料
            for (int i = 0; i < diff.size(); i++) {
                CompareReportVO compareReportVO = diff.get(i);
                if (compareReportVO.getChildPartDiff() != null) {
                    if (compareReportVO.getChildPartDiff().size() > 0) {

                        boolean jy=false;
                        Map<String, Object> addPartDiffMapMap = new HashMap<>();
                        for (int y = 0; y < compareReportVO.getChildPartDiff().size(); y++) {
                            ObjRefDiffVO objRefDiffVO = compareReportVO.getChildPartDiff().get(y);
                            if ("add".equals(objRefDiffVO.getAction())) {
                                addPartDiffMapMap.put(objRefDiffVO.getObjectNumber(), "1");
                            }
                            if("delete".equals(objRefDiffVO.getAction())){
                                jy=true;
                            }
                        }

                        BigInteger oid = compareReportVO.getRightPartOid();
                        PartDetailsVO partDetailsVO = plmPartOptionUtils.getPartDetailsVO(oid, null);
                        com.hustcad.plm.pdm.partbom.dto.ExpandBomTreeByFilterDTO expandBomTreeByFilterDTO = new com.hustcad.plm.pdm.partbom.dto.ExpandBomTreeByFilterDTO();
                        expandBomTreeByFilterDTO.setAttrFilterCondition(new ArrayList<>());

                        ChildPartsFiltersDTO childPartsFiltersDTO = new ChildPartsFiltersDTO();
                        childPartsFiltersDTO.setBaseLineOid("");
                        childPartsFiltersDTO.setDate("");
                        childPartsFiltersDTO.setExpandCondition("latest");
                        childPartsFiltersDTO.setLifecycleStateKey("");
                        childPartsFiltersDTO.setPurposeOfBom("");
                        childPartsFiltersDTO.setSpareBom("");
                        childPartsFiltersDTO.setView(partDetailsVO.getView());
                        List<ChildPartsFiltersDTO> list = new ArrayList<>();
                        list.add(childPartsFiltersDTO);
                        expandBomTreeByFilterDTO.setConditions(list);

                        expandBomTreeByFilterDTO.setExpandLevel("1");
                        expandBomTreeByFilterDTO.setFatherNumber(partDetailsVO.getObjectNumber());
                        expandBomTreeByFilterDTO.setFatherOid(String.valueOf(partDetailsVO.getOid()));
                        expandBomTreeByFilterDTO.setFatherOtype(partDetailsVO.getOtype());
                        expandBomTreeByFilterDTO.setFilterMode("0");
                        expandBomTreeByFilterDTO.setGiveUsesOccurrence("N");
                        expandBomTreeByFilterDTO.setIbaColumns(new ArrayList<>());
                        expandBomTreeByFilterDTO.setIsApplyRoot(false);
                        expandBomTreeByFilterDTO.setIsFilterAttr(false);
                        expandBomTreeByFilterDTO.setIsNeedTranEnum(true);
                        expandBomTreeByFilterDTO.setIsNestedTree(false);
                        expandBomTreeByFilterDTO.setIsQueryIBA(true);

                        PartBomTreeByFilterVO result = typlmPartBomService.expandBomTreeByFilterNew(
                                expandBomTreeByFilterDTO, Boolean.TRUE);

                        if (result.getPartBomTreeList().size() > 1) {
                            PartBomTree parentPartBomTree = null;
                            HashSet<PartBomTree> children = new LinkedHashSet<>();

                            for (int a = 0; a < result.getPartBomTreeList().size(); a++) {
                                PartBomTree partBomTree = result.getPartBomTreeList().get(a);
                                BigInteger addOid = new BigInteger(partBomTree.getPartoid());
                                String addOtype = partBomTree.getPartotype();
                                PartDetailsVO addPartDetailsVO = plmPartOptionUtils.getPartDetailsVO(addOid, addOtype);

                                if (addPartDiffMapMap.containsKey(
                                        result.getPartBomTreeList().get(a).getObjectNumber())) {
                                    //添加物料到物料列表，用于构建批量物料保存数据
                                    partDetailsVOList.add(addPartDetailsVO);
                                }
                                //构建bomTreeList,用于构建BOM数据
                                if (partBomTree.getOid() == BigInteger.valueOf(0L)) {
                                    parentPartBomTree = partBomTree;
                                } else {
                                    children.add(partBomTree);
                                }
                            }
                            parentPartBomTree.setChildren(children);
                            bomTreeList.add(parentPartBomTree);
                        }
                        else{
                            if(jy){
                                jyList.add(partDetailsVO);
                            }
                        }

                    }

                }
            }

            //获取替代相关信息
            Map<String, Object> alternativeMap = getChangesObject(flowChgFormView);

            List<PartDetailsVO> alternativePartDetailsVOList = (List<PartDetailsVO>) alternativeMap.get(
                    "alternativePartDetailsVOList");
            List<Map<String, Object>> addAlternativeList = (List<Map<String, Object>>) alternativeMap.get(
                    "addAlternativeList");

            partDetailsVOList.addAll(alternativePartDetailsVOList);

            List<PartBomTree> addBomTreeList = new ArrayList<>();

            List<PartBomTree> tdBomTreeList = (List<PartBomTree>) alternativeMap.get("bomTreeList");
            Map<String, Object> tdBomMap = new HashMap<>();

            for (int i = 0; i < bomTreeList.size(); i++) {
                PartBomTree partBomTree = bomTreeList.get(i);
                if (tdBomMap.containsKey(partBomTree.getObjectNumber())) {
                    continue;
                }
                tdBomMap.put(partBomTree.getObjectNumber(), 1);
                addBomTreeList.add(partBomTree);

            }

            for (int i = 0; i < tdBomTreeList.size(); i++) {
                PartBomTree partBomTree = tdBomTreeList.get(i);
                if (tdBomMap.containsKey(partBomTree.getObjectNumber())) {
                    continue;
                }
                tdBomMap.put(partBomTree.getObjectNumber(), 1);
                addBomTreeList.add(partBomTree);

            }
            for (int i = 0; i < AllBomTreeList.size(); i++) {
                PartBomTree partBomTree = AllBomTreeList.get(i);
                if (tdBomMap.containsKey(partBomTree.getObjectNumber())) {
                    continue;
                }
                tdBomMap.put(partBomTree.getObjectNumber(), 1);
                addBomTreeList.add(partBomTree);

            }
            //禁用列表
            resultMap.put("jyList", jyList);

            //需新增的物料
            resultMap.put("add", partDetailsVOList);

            //需要维护的替代料
            resultMap.put("addAlternativeList", addAlternativeList);

            //需要反审核的替代料
            resultMap.put("deleteAlternativeMap", alternativeMap.get("deleteAlternativeMap"));

            //需要修改的BOM
            resultMap.put("updateBom", addBomTreeList);
            resultMap.put("baseLine", baseLineMap);

            return resultMap;
        }
        return null;
    }

    /**
     * 获取替代件的物料和替代关系和需要反审核的替代方案
     *
     * @param flowChgFormView
     * @return
     * @throws Exception
     */
    public Map<String, Object> getChangesObject(FlowChgFormView flowChgFormView) throws Exception {
        TyplmPdmPartAlternateService typlmPartAlternateService = SpringUtil.getBean(TyplmPdmPartAlternateService.class);
        PlmPartOptionUtils plmPartOptionUtils = SpringUtil.getBean(PlmPartOptionUtils.class);
        TyplmPartBomService typlmPartBomService = SpringUtil.getBean(TyplmPartBomService.class);
        TyplmPdmPartSubstituteService typlmPartSubstituteService = SpringUtil.getBean(
                TyplmPdmPartSubstituteService.class);
        ErpPartAlternativeService erpPartAlternativeService = SpringUtil.getBean(ErpPartAlternativeService.class);

        UserDO userDO = TyAccountContext.getUser();

        if (flowChgFormView.getChgFormVO() != null && flowChgFormView.getChgFormVO().getEcAffectVOS() != null) {

            List<Map<String, Object>> addAlternativeList = new ArrayList<>();
            List<ParentPartDetailVO> pBomlist = new ArrayList<>();
            Map<String, List<PartSubstituteVO>> newUnAuditMap = new HashMap<>();
            Map<String, List<PartSubstituteVO>> oldUnAuditMap = new HashMap<>();

            for (int i = 0; i < flowChgFormView.getChgFormVO().getEcAffectVOS().size(); i++) {
                ECObjData ecObjData = flowChgFormView.getChgFormVO().getEcAffectVOS().get(i);
                if ("ty.inteplm.part.CTyPart".equals(ecObjData.getOtype())) {
                    //变更后对象
                    //查询全局替代件
                    List<String> alternateForPartNumbers = new ArrayList<>();
                    alternateForPartNumbers.add(ecObjData.getNumber());
                    List<AlternateInfoVO> listAlternates = typlmPartAlternateService.batchQueryAlternates(
                            alternateForPartNumbers);

                    QuerySubstituteLinkDTO querySubstituteLinkDTO = new QuerySubstituteLinkDTO();
                    if (ObjectUtils.isNotEmpty(userDO) && ObjectUtils.isNotEmpty(userDO.getOid())) {
                        querySubstituteLinkDTO.setUserOid(userDO.getOid());
                    }
                    querySubstituteLinkDTO.setBnumber(String.valueOf(ecObjData.getNumber()));
                    querySubstituteLinkDTO.setBoid(String.valueOf(ecObjData.getOid()));

                    BigInteger newOid = ecObjData.getOid();
                    String newOtype = ecObjData.getOtype();
                    PartDetailsVO partDetails = plmPartOptionUtils.getPartDetailsVO(newOid, newOtype);

                    List<PartSubstituteVO> listSubstitute = typlmPartSubstituteService.queryPartSubstituteLink(
                            querySubstituteLinkDTO);

                    //移除旧版本的替代关系
                    if (listSubstitute.size() > 0) {
                        List<BigInteger> partList = new ArrayList<>();
                        partList.add(ecObjData.getRefObjectOid());
                        List<ParentPartDetailVO> plist = typlmPartBomService.queryParentPartByFilter(partList);
                        if (plist.size() > 0) {
                            for (int a = 0; a < listSubstitute.size(); a++) {
                                String version = listSubstitute.get(a).getUsageAversion();
                                String aiteration = listSubstitute.get(a).getUsageAiteration();
                                ParentPartDetailVO parentPartDetailVO = plist.get(0);
                                String pVersion = parentPartDetailVO.getVersion();
                                String piteration = parentPartDetailVO.getIterationid();
                                if (version.equals(pVersion) == false || aiteration.equals(piteration) == false) {
                                    listSubstitute.remove(a);
                                    a--;
                                }
                            }
                        }

                    }
                    if (listSubstitute.size() > 0) {
                        newUnAuditMap.put(partDetails.getObjectNumber(), listSubstitute);
                    }


                    Map<String, Object> alternative = new HashMap<>();
                    if (listAlternates != null && listAlternates.size() > 0) {
                        boolean isUpdate = false;
                        for (int a = 0; a < listAlternates.size(); a++) {
                            AlternateInfoVO alternateInfoVO = listAlternates.get(a);

                            Map<String, List<String>> allTd = alternateInfoVO.getIbaAttributeMap();
                            if (allTd != null) {
                                if (allTd.containsKey("替代方案编码")) {
                                    List<String> cList = allTd.get("替代方案编码");
                                    if (cList.size() == 0 || "".equals(cList.get(0))) {
                                        isUpdate = true;
                                        break;
                                    }
                                }
                            } else {
                                isUpdate = true;
                            }
                        }
                        if (isUpdate) {
                            alternative.put("listAlternates", listAlternates);
                        }
                    }
                    if (listSubstitute != null && listSubstitute.size() > 0) {
                        boolean isUpdate = false;
                        for (int a = 0; a < listSubstitute.size(); a++) {
                            PartSubstituteVO partSubstituteVO = listSubstitute.get(a);

                            Map<String, List<String>> allTd = partSubstituteVO.getIbaAttributeMap();
                            if (allTd != null) {
                                if (allTd.containsKey("替代方案编码")) {
                                    List<String> cList = allTd.get("替代方案编码");
                                    if (cList.size() == 0 || "".equals(cList.get(0))) {
                                        isUpdate = true;
                                        break;
                                    }
                                }
                            } else {
                                isUpdate = true;
                            }
                        }
                        if (isUpdate) {
                            alternative.put("listSubstitute", listSubstitute);
                        }
                    }
                    if (alternative.size() > 0) {
                        alternative.put("partDetails", partDetails);
                        if ("已发布".equals(partDetails.getLifecycleState()) == false) {
                            addAlternativeList.add(alternative);
                            List<BigInteger> partList = new ArrayList<>();
                            partList.add(ecObjData.getRefObjectOid());
                            List<ParentPartDetailVO> plist = typlmPartBomService.queryParentPartByFilter(partList);
                            pBomlist.addAll(plist);
                        }
                    }

                }
            }

            for (int i = 0; i < flowChgFormView.getChgFormVO().getEcObjDataVOS().size(); i++) {
                ECObjData ecObjData = flowChgFormView.getChgFormVO().getEcObjDataVOS().get(i);
                if ("ty.inteplm.part.CTyPart".equals(ecObjData.getOtype())) {
                    //变更前对象
                    QuerySubstituteLinkDTO querySubstituteLinkDTO = new QuerySubstituteLinkDTO();
                    if (ObjectUtils.isNotEmpty(userDO) && ObjectUtils.isNotEmpty(userDO.getOid())) {
                        querySubstituteLinkDTO.setUserOid(userDO.getOid());
                    }
                    querySubstituteLinkDTO.setBnumber(String.valueOf(ecObjData.getNumber()));
                    querySubstituteLinkDTO.setBoid(String.valueOf(ecObjData.getOid()));


                    List<PartSubstituteVO> listSubstitute = typlmPartSubstituteService.queryPartSubstituteLink(
                            querySubstituteLinkDTO);

                    //移除旧版本的替代关系
                    if (listSubstitute.size() > 0) {
                        oldUnAuditMap.put(ecObjData.getObjectNumber(), listSubstitute);
                    }
                }
            }

            Map<String, List<PartSubstituteVO>> deleeUnAuditMap = new HashMap<>();

            for (Map.Entry<String, List<PartSubstituteVO>> entity : oldUnAuditMap.entrySet()) {
                if (newUnAuditMap.containsKey(entity.getKey()) == false) {
                    List<PartSubstituteVO> listSubstitute = entity.getValue();
                    for (int s = 0; s < listSubstitute.size(); s++) {
                        PartSubstituteVO partSubstituteVO = listSubstitute.get(s);
                        String plmFSubstitutionId = null;
                        Map<String, List<String>> baAttributeMap = partSubstituteVO.getIbaAttributeMap();
                        if (baAttributeMap != null) {
                            if (baAttributeMap.containsKey("替代方案编码")) {
                                List<String> cList = baAttributeMap.get("替代方案编码");
                                if (cList.size() > 0 && "".equals(cList.get(0)) == false) {
                                    plmFSubstitutionId = cList.get(0);
                                    deleeUnAuditMap.put(plmFSubstitutionId, entity.getValue());
                                }
                            }
                        }
                    }
                }
            }


            List<PartDetailsVO> partDetailsVOList = new ArrayList<>();
            List<PartBomTree> bomTreeList = new LinkedList<>();

            //获取创建替代件物料
            for (int i = 0; i < addAlternativeList.size(); i++) {
                Map<String, Object> alternative = addAlternativeList.get(i);
                List<AlternateInfoVO> listAlternates = (List<AlternateInfoVO>) alternative.get("listAlternates");
                List<PartSubstituteVO> listSubstitute = (List<PartSubstituteVO>) alternative.get("listSubstitute");
                if (listAlternates != null) {
                    for (int a = 0; a < listAlternates.size(); a++) {
                        AlternateInfoVO alternateInfoVO = listAlternates.get(a);
                        List<Map<String, Object>> erpList = erpPartAlternativeService.getPartDetailsBylinkOid(
                                new BigInteger(alternateInfoVO.getId()));
                        if (erpList.size() > 0) {
                            BigInteger oid = new BigInteger(String.valueOf(erpList.get(0).get("linkpartoid")));
                            String oType = (String) erpList.get(0).get("linkotype");
                            PartDetailsVO linkPartDetailsVO = plmPartOptionUtils.getPartDetailsVO(oid, oType);
                            partDetailsVOList.add(linkPartDetailsVO);
                        }
                    }
                }
                if (listSubstitute != null) {
                    for (int a = 0; a < listSubstitute.size(); a++) {
                        PartSubstituteVO partSubstituteVO = listSubstitute.get(a);
                        List<Map<String, Object>> erpList = erpPartAlternativeService.getPartDetailsBySubstituteLinkOid(
                                new BigInteger(partSubstituteVO.getLinkId()));
                        if (erpList.size() > 0) {
                            BigInteger oid = new BigInteger(String.valueOf(erpList.get(0).get("linkpartoid")));
                            String oType = (String) erpList.get(0).get("linkotype");
                            PartDetailsVO linkPartDetailsVO = plmPartOptionUtils.getPartDetailsVO(oid, oType);
                            partDetailsVOList.add(linkPartDetailsVO);
                        }
                    }
                }
            }

            Map<String, Object> cmdMap = new HashMap<>();

            for (int i = 0; i < pBomlist.size(); i++) {
                if (cmdMap.containsKey(pBomlist.get(i).getObjectNumber())) {
                    continue;
                }
                cmdMap.put(pBomlist.get(i).getObjectNumber(), 1);

                ParentPartDetailVO parentPartDetailVO = pBomlist.get(i);

                com.hustcad.plm.pdm.partbom.dto.ExpandBomTreeByFilterDTO expandBomTreeByFilterDTO = new com.hustcad.plm.pdm.partbom.dto.ExpandBomTreeByFilterDTO();
                expandBomTreeByFilterDTO.setAttrFilterCondition(new ArrayList<>());

                ChildPartsFiltersDTO childPartsFiltersDTO = new ChildPartsFiltersDTO();
                childPartsFiltersDTO.setBaseLineOid("");
                childPartsFiltersDTO.setDate("");
                childPartsFiltersDTO.setExpandCondition("latest");
                childPartsFiltersDTO.setLifecycleStateKey("");
                childPartsFiltersDTO.setPurposeOfBom("");
                childPartsFiltersDTO.setSpareBom("");
                childPartsFiltersDTO.setView(parentPartDetailVO.getView());
                List<ChildPartsFiltersDTO> list = new ArrayList<>();
                list.add(childPartsFiltersDTO);
                expandBomTreeByFilterDTO.setConditions(list);

                expandBomTreeByFilterDTO.setExpandLevel("1");
                expandBomTreeByFilterDTO.setFatherNumber(parentPartDetailVO.getObjectNumber());
                expandBomTreeByFilterDTO.setFatherOid(String.valueOf(parentPartDetailVO.getOid()));
                expandBomTreeByFilterDTO.setFatherOtype(parentPartDetailVO.getOtype());
                expandBomTreeByFilterDTO.setFilterMode("0");
                expandBomTreeByFilterDTO.setGiveUsesOccurrence("N");
                expandBomTreeByFilterDTO.setIbaColumns(new ArrayList<>());
                expandBomTreeByFilterDTO.setIsApplyRoot(false);
                expandBomTreeByFilterDTO.setIsFilterAttr(false);
                expandBomTreeByFilterDTO.setIsNeedTranEnum(true);
                expandBomTreeByFilterDTO.setIsNestedTree(true);
                expandBomTreeByFilterDTO.setIsQueryIBA(true);

                PartBomTreeByFilterVO result = typlmPartBomService.expandBomTreeByFilterNew(expandBomTreeByFilterDTO,
                                                                                            Boolean.TRUE);
                if (result.getPartBomTreeList().size() > 0) {
                    bomTreeList.add(result.getPartBomTreeList().get(0));
                }

            }

            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("alternativePartDetailsVOList", partDetailsVOList);
            resultMap.put("addAlternativeList", addAlternativeList);
            resultMap.put("bomTreeList", bomTreeList);

            if (deleeUnAuditMap.size() > 0) {
                resultMap.put("deleteAlternativeMap", deleeUnAuditMap);
            }

            return resultMap;
        }
        return null;
    }
}
